import pickle

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from redis import StrictRedis

from goods.models import SKU


class CartsView(APIView):
    """购物车管理"""

    def post(self, request):
        """添加购物车"""
        # sku_id=1  商品id
        # count=2 数量
        # selected=True 是否选择
        sku_id = request.data.get('sku_id')
        count = request.data.get('count')
        user = request.user

        """
            1. 勾选状态, 
            2. sku_id
            3. 数量
            {
                1:{count:1, selected: True},
                2:{count:1, selected: True},
                3:{count:1, selected: True},
            }

            mysql,  存特别久
            redis,  存一定时间就可以, 性能高

        """
        redis_client = StrictRedis()  # 建立redis客户端,
        carts_bytes = redis_client.get(str(user.id) + '_carts')
        # 取  用户id+'_carts'  这个键的值,
        # user.id  =>  1
        # 1_carts
        # user.id =>
        # 2_carts
        if carts_bytes:
            carts = pickle.loads(carts_bytes)
        else:
            carts = {}

        # 给购物车添加数据
        """
        {
                (sku_id)1:{count:1, selected: True},
                2:{count:1, selected: True},
                3:{count:1, selected: True},
        }"""
        carts[sku_id] = {'count': count, 'selected': True}

        carts_bytes = pickle.dumps(carts)

        redis_client.set(str(user.id) + '_carts', carts_bytes)

        return Response({'msg': '添加成功'})

    def get(self, request):
        # 1. 获取用户id
        user = request.user

        # 2. 获取redis中的购物车数据
        redis_client = StrictRedis()
        redis_carts = redis_client.get(str(user.id) + '_carts')
        if redis_carts:
            carts = pickle.loads(redis_carts)
        else:
            carts = {}
            return Response({'msg': '购物车为空'})
        # 3. 返回购物车中的内容给前端,
        # [{sku_img:xxxx, sku_id:xxxx,  sku_name:xxxx, sku_price:xx , count:12, selected:True},{}]
        # 1:{count:1, selected: True},
        sku_list = []
        for sku_id, count_selected in carts.items():
            sku = SKU.objects.get(id=sku_id)
            sku_data = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'count': count_selected['count'],
                'selected': count_selected['selected'],
                'default_image_url': sku.default_image_url.url
                # default_image_url是路径, 没有前缀,  default_image_url.url(), 是完整路径, 前端需要完整路径
            }
            sku_list.append(sku_data)
        return Response({'code': 0, 'msg': '购物车获取成功', 'data': sku_list})

    def delete(self, request):
        # 删除购物车商品
        # 1. 获取用户id,  sku_id
        user = request.user
        sku_id = request.data.get('sku_id')

        # 2. 取redis购物车数据
        redis_client = StrictRedis()  # 建立redis客户端,
        carts_bytes = redis_client.get(str(user.id) + '_carts')
        if carts_bytes:
            carts = pickle.loads(carts_bytes)
        else:
            carts = {}
            return Response({'code': 0, 'msg': '购物车中不存在此商品'})

        # 3. 删除购物车中的数据
        """
        {
                1:{count:1, selected: True},

                3:{count:1, selected: True},
        }"""
        if carts.get(sku_id, None):
            del carts[sku_id]
            carts_bytes = pickle.dumps(carts)
            # 4. 再存入redis中
            redis_client.set(str(user.id) + '_carts', carts_bytes)
            # 5. 返回成功
            return Response({'code': 0, 'msg': '删除成功'})
        else:
            return Response({'code': 0, 'msg': '购物车中不存在此商品'})

    def put(self, request):
        # 1. 获取用户, sku_id, count, selected
        user = request.user
        sku_id = request.data.get('sku_id')
        count = request.data.get('count')
        selected = request.data.get('selected')  # True,  False
        if all([sku_id, count, str(selected)]):
            pass
        else:
            return Response({'code': 999, 'msg': '缺少参数'})

        # 2. 取redis购物车数据
        redis_client = StrictRedis()  # 建立redis客户端,
        carts_bytes = redis_client.get(str(user.id) + '_carts')
        if carts_bytes:
            carts = pickle.loads(carts_bytes)
        else:
            carts = {}
            return Response({'code': 0, 'msg': '购物车中不存在此商品'})

        # 3. 修改购物车
        sku_data = carts.get(sku_id, None)
        if sku_data:
            """
            {
                    1:{count:1, selected: True},

                    3:{count:1, selected: True},
            }"""
            sku_data['count'] = count
            sku_data['selected'] = selected
            # 4. 保存到redis中
            carts_bytes = pickle.dumps(carts)

            redis_client.set(str(user.id) + '_carts', carts_bytes)
            # 5. 返回成功
            return Response({'code': 0, 'msg': '修改成功'})
        else:
            return Response({'code': 0, 'msg': '购物车中不存在此商品'})

    def patch(self, request):
        # 1 . 获取用户, 和selected
        user = request.user
        selected = request.data.get('selected')  # True,  False
        print(selected)

        # 2.  获取购物车信息
        redis_client = StrictRedis()  # 建立redis客户端,
        carts_bytes = redis_client.get(str(user.id) + '_carts')
        if carts_bytes:
            carts = pickle.loads(carts_bytes)
        else:
            carts = {}
            return Response({'code': 0, 'msg': '购物车中不存在商品'})
        # 3. 修改购物车所有商品的选择状态为 传过来的状态
        """
        {
            1:{count:1, selected: True},
            3:{count:1, selected: True},
        }
        """
        for sku_id, count_selected in carts.items():
            count_selected['selected'] = selected
        # 4. 保存到redis
        carts_bytes = pickle.dumps(carts)

        redis_client.set(str(user.id) + '_carts', carts_bytes)
        # 5. 返回成功
        return Response({'code': 0, 'msg': '修改成功'})
